<template>
  <div class="role-manager-container">
    <div class="set-icon-header">
      <el-form
        ref="form"
        label-position="left"
        :model="personManagerSearch"
        label-width="70px"
      >
        <el-row :gutter="15">
          <el-col :span="7">
            <el-form-item label="客户：">
              <el-input v-model="personManagerSearch.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label-width="100px" label="类别：">
              <el-select style="width: 220px;" v-model="personManagerSearch.customerType" placeholder="请选择">
                <el-option
                  v-for="item in [{label: '全部', value: ''},{label: '普通用户', value: 0},{label: '企业用户', value: 1}]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="星级：">
              <el-select style="width: 220px;" v-model="personManagerSearch.star" placeholder="请选择">
                <el-option
                  v-for="item in [{label: '全部', value: ''},{label: '一星', value: 1},{label: '二星', value: 2},{label: '三星', value: 3},{label: '四星', value: 4},{label: '五星', value: 5}]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="7">
            <el-form-item label="创建人：">
              <el-input v-model="personManagerSearch.createBy" />
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label-width="100px" label="创建时间：">
              <el-date-picker
                v-model="personManagerSearch.createTime"
                type="date"
                placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="手机号：">
              <el-input style="width: 220px;" v-model="personManagerSearch.phone" />
            </el-form-item>
          </el-col>
        </el-row>

        <div @click="queryMethods" class="query-customer-button">
          <div>查询</div>
        </div>
      </el-form>
    </div>

    <div style="margin: 16px 0;">
      <div @click="addNewPersonMethods" class="add-customer-button">
        <img src="@/assets/add_12@2x.png" class="add-customer-icon" alt="">
        <div>新增客户</div>
      </div>
    </div>

    <div class="set-icon-header">
      <CommonTable
        v-loading="isLoading"
        style="margin-top: 15px"
        :is-selection="false"
        :is-show-index="true"
        :t-column-data="customerManager"
        :t-data="customerManagerList"
        :is-has-opera="true"
        :is-reserve-select="true"
        row-key="userId"
        @changeRow="changeSelectionList"
      >
        <template slot="starSlot" slot-scope="scope">
          <img v-if="scope.row.setIcon" :src="scope.row.setIcon" alt="">
        </template>
        <template slot="customerStatusSlot" slot-scope="scope">
          <template v-if="!scope.row.warning">
            <span v-if="scope.row.customerStatus == 1" class="dot-class dot-gray">

            </span>
            <span v-if="scope.row.customerStatus == 0" class="dot-class dot-green">

            </span>
            <span>
            {{['正常', '冻结'][scope.row.customerStatus]}}
            </span>
          </template>
          <template v-else>
            <span style="color: #F56C6C;">
              即将过期
            </span>
          </template>
        </template>
        <template slot="expirationSlot" slot-scope="scope">
          <span :style="scope.row.warning?'color: #F56C6C;': ''">
              {{ scope.row.expiration }}
          </span>
        </template>
        <template
          slot="operate"
          slot-scope="scope"
        >
          <div class="do-list" v-if="scope.row.userId !== 1">
          <span
            @click="editPersonDetail(scope.row)"
          >编辑</span>
            <span
              v-if="scope.row.customerStatus == 0"
              @click="freezePerson(scope.row, 1)"
            >冻结</span>

            <span
              v-if="scope.row.customerStatus == 1"
              @click="freezePerson(scope.row, 0)"
            >解冻</span>

            <span
              @click="lookPersonDetail(scope.row)"
            >查看用户</span>

            <span
              class="del-button"
              @click="delPersonDetail(scope.row)"
            >删除</span>
          </div>
        </template>
      </CommonTable>
    </div>

    <el-pagination
      class="page-nation"
      :current-page="personManagerSearch.pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="personManagerSearch.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      :title="customerModalTitle"
      :visible.sync="isShowAddCustomer"
      width="65%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        v-loading="isLoading"
        v-if="isShowAddCustomer"
        ref="addUsersForm"
        :model="addPersonModel"
        label-position="left"
        class="demo-ruleForm"
        :rules="usersAddrules"
        label-width="90px"
      >
        <div class="customer-label-title">
          基础信息
        </div>
        <el-row :gutter="10" v-if="addCustomType === 'company'">
          <el-col :span="12">
            <el-form-item
              label="企业名称"
              prop="enterpriseName"
            >
              <el-input v-if="openDetailType === 'edit'" v-model="addPersonModel.enterpriseName" />
              <span v-else>
                {{addPersonModel.enterpriseName}}
              </span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="营业执照"
            >
              <el-upload
                v-if="openDetailType === 'edit'"
                class="avatar-uploader"
                action=""
                accept=".jpg,.png,.jpeg,.JPG,.PNG,.JPEG"
                :show-file-list="false"
                v-loading="uploadLoading"
                :before-upload="beforeUploadMethods"
                :http-request="
            (file) => {
              this.uploadforwardIconUrl(file, 'businessLicense');
            }
          "
              >
                <i
                  v-if="!addPersonModel.businessLicense"
                  slot="default"
                  class="el-icon-plus avatar-uploader-icon"
                ></i>
                <img
                  v-if="addPersonModel.businessLicense"
                  :src="addPersonModel.businessLicense"
                  alt=""
                  class="avatar"
                />
              </el-upload>
              <div v-else>
                <el-image
                  v-if="addPersonModel.businessLicense"
                  style="width: 240px; height: 240px"
                  :src="addPersonModel.businessLicense"
                  :preview-src-list="[addPersonModel.businessLicense]">
                </el-image>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item
              label="联系人"
              prop="contacts"
            >
              <el-input v-if="openDetailType === 'edit'" v-model="addPersonModel.contacts" />
              <span v-else>
                {{addPersonModel.contacts}}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="openDetailType === 'edit'">
            <el-form-item
              label="登录密码"
              :prop="addPersonModel.userId?'': 'password'"
            >
              <el-input
                type="text"
                id="passwordVal"
                v-model.trim="addPersonModel.password"
                maxlength="8"
                show-word-limit
                style="width: 42%"
              />
              <el-button @click="createRandomNumber" style="margin-left: 10px;" type="primary">随机生成</el-button>
<!--              <el-button @click="copyPassMethods" type="text">复制</el-button>-->
              <span class="copy-words" @click="copyPassMethods">复制</span>

              <input id="copy" class="copyInput" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="联系方式"
          prop="phone"
        >
          <el-input
            v-model.trim="addPersonModel.phone"
            maxlength="11"
            show-word-limit
            v-if="openDetailType === 'edit'"
            style="width: 44%"
          />
          <span v-else>
            {{addPersonModel.phone}}
          </span>
        </el-form-item>


        <el-form-item v-if="addCustomType === 'person'" label="身份证号码">
          <el-input
            v-model.trim="addPersonModel.idCardNo"
            maxlength="18"
            v-if="openDetailType === 'edit'"
            show-word-limit
            style="width: 44%"
          />
          <span v-else>
            {{addPersonModel.idCardNo}}
          </span>
        </el-form-item>

        <el-row v-if="addCustomType === 'person'" :gutter="10">
          <el-col :span="12">
            <el-form-item label="身份证正面">
              <el-upload
                v-if="openDetailType === 'edit'"
                class="avatar-uploader"
                action=""
                accept=".jpg,.png,.jpeg,.JPG,.PNG,.JPEG"
                :show-file-list="false"
                v-loading="uploadLoading"
                :before-upload="beforeUploadMethods"
                :http-request="
            (file) => {
              this.uploadforwardIconUrl(file, 'idCardFront');
            }
          "
              >
                <i
                  v-if="!addPersonModel.idCardFront"
                  slot="default"
                  class="el-icon-plus avatar-uploader-icon"
                ></i>
                <img
                  v-if="addPersonModel.idCardFront"
                  :src="addPersonModel.idCardFront"
                  alt=""
                  class="avatar"
                />
              </el-upload>
              <div v-else>
                <el-image
                  v-if="addPersonModel.idCardFront"
                  style="width: 240px; height: 240px"
                  :src="addPersonModel.idCardFront"
                  :preview-src-list="[addPersonModel.idCardFront]">
                </el-image>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证反面">
              <el-upload
                v-if="openDetailType === 'edit'"
                class="avatar-uploader"
                action=""
                accept=".jpg,.png,.jpeg,.JPG,.PNG,.JPEG"
                :show-file-list="false"
                v-loading="uploadLoading"
                :before-upload="beforeUploadMethods"
                :http-request="
            (file) => {
              this.uploadforwardIconUrl(file, 'idCardBack');
            }
          "
              >
                <i
                  v-if="!addPersonModel.idCardBack"
                  slot="default"
                  class="el-icon-plus avatar-uploader-icon"
                ></i>
                <img
                  v-if="addPersonModel.idCardBack"
                  :src="addPersonModel.idCardBack"
                  alt=""
                  class="avatar"
                />
              </el-upload>
              <div v-else>
                <el-image
                  v-if="addPersonModel.idCardBack"
                  style="width: 240px; height: 240px"
                  :src="addPersonModel.idCardBack"
                  :preview-src-list="[addPersonModel.idCardBack]">
                </el-image>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item
              label="推荐人"
            >
              <el-input
                v-model.trim="addPersonModel.referrer"
                v-if="openDetailType === 'edit'"
              />
              <span v-else>
            {{addPersonModel.referrer}}
          </span>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="客户经理"
            >
<!--              <el-input-->
<!--                v-model.trim="addPersonModel.referrer"-->
<!--                v-if="openDetailType === 'edit'"-->
<!--              />-->
              <el-select v-if="openDetailType === 'edit'" v-model="addPersonModel.managerId" placeholder="请选择">
                <el-option
                  v-for="item in personManagerList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId">
                </el-option>
              </el-select>
<!--              personManagerList-->
              <span v-else>
                {{currentManagerName}}
              </span>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="customer-label-title">
          会员类型
        </div>

        <el-form label-position="left" label-width="80px">
          <el-form-item label="开通时间">
            <el-row>
              <el-col :span="6">
                <el-select v-if="openDetailType === 'edit'" v-model="openTimeModel" placeholder="请选择">
                  <el-option
                    v-for="item in openTimeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>

                <span v-else>
                  {{openTimeModelText}}
                </span>
              </el-col>

              <el-col :span="12">
<!--                <el-date-picker-->
<!--                  v-if="openTimeModel == 4"-->
<!--                  v-model="endDate"-->
<!--                  type="datetime"-->
<!--                  placeholder="选择日期时间">-->
<!--                </el-date-picker>-->

                <el-date-picker
                  v-model="selectTimer"
                  v-if="openTimeModel == 4"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>

              </el-col>
            </el-row>
          </el-form-item>
        </el-form>

        <div class="customer-type-card-row">
          <div
            v-for="(item, index) in meetingServiceInfo"
            @click="activeMeetingInfo(index)"
            :class="item.active?'customer-type-card-col-active customer-type-card-col': 'customer-type-card-col'"
          >
            <div :class="index == 0?'first-words': index == 1? 'second-words': 'default-words'">{{item.title}}</div>

<!--            <div class="content-bottom-row">-->
<!--              <div class="flex-common">-->
<!--                <img src="@/assets/icon_cbhy@2x.png" class="left-icon-image" alt="">-->

<!--                <div>创办会议</div>-->
<!--              </div>-->
<!--              <div class="content-button-col-right">无限</div>-->
<!--            </div>-->

<!--            <div class="content-bottom-row">-->
<!--              <div class="flex-common">-->
<!--                <img src="@/assets/icon_hwfu@2x.png" class="left-icon-image" alt="">-->
<!--                <div>会务服务</div>-->
<!--              </div>-->
<!--              <div class="content-button-col-right">无限</div>-->
<!--            </div>-->

<!--            <div class="content-bottom-row">-->
<!--              <div class="flex-common">-->
<!--                <img src="@/assets/icon_hypz@2x.png" class="left-icon-image" alt="">-->
<!--                <div>会议排座</div>-->
<!--              </div>-->
<!--              <div class="content-button-col-right">无限</div>-->
<!--            </div>-->

<!--            <div class="content-bottom-row">-->
<!--              <div class="flex-common">-->
<!--                <img src="@/assets/icon_zskf@2x.png" class="left-icon-image" alt="">-->
<!--                <div>专属客服</div>-->
<!--              </div>-->
<!--              <div class="content-button-col-right">7*24小时</div>-->
<!--            </div>-->

<!--            <el-button>开通</el-button>-->

            <el-rate :disabled="true" v-model="item.star"></el-rate>
            <div class="other-words">
              定价: {{item.price}}
            </div>
            <div class="other-words">
              周期: {{item.period}}年
            </div>
          </div>
        </div>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <div class="footer-bottom-flex">
          <div style="margin-right: 10px;" @click="submitAddNewCustomer" class="query-common-small-customer-button">
            <div>确定</div>
          </div>
          <div @click="handleClose" class="query-default-small-customer-button">
            <div>取消</div>
          </div>
        </div>

<!--        <el-button @click="handleClose">取 消</el-button>-->
<!--        <el-button-->
<!--          v-if="openDetailType === 'edit'"-->
<!--          type="primary"-->
<!--          @click="submitAddNewCustomer"-->
<!--        >确 定</el-button>-->
      </span>
    </el-dialog>

    <el-dialog
      :title="addPersonModel.userId?'编辑客户':'新增客户'"
      :visible.sync="isShowAddCustomerSelect"
      width="20%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <div style="text-align: center;">
        <el-radio v-model="addCustomType" label="company">企业用户</el-radio>
        <el-radio v-model="addCustomType" label="person">普通用户</el-radio>
<!--        <el-button @click="addNewCustomerPerson('company')" type="primary">企业用户</el-button>-->
<!--        <el-button @click="addNewCustomerPerson('person')" type="primary">普通用户</el-button>-->
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <div class="footer-bottom-flex">
          <div style="margin-right: 10px;" @click="addNewCustomerPerson" class="query-common-small-customer-button">
            <div>确定</div>
          </div>
          <div @click="handleClose" class="query-default-small-customer-button">
            <div>取消</div>
          </div>
        </div>
<!--        <el-button @click="handleClose">取 消</el-button>-->
      </span>
    </el-dialog>

    <el-dialog
      title=""
      :visible.sync="isShowFree"
      width="20%"
      :before-close="handleClose"
    >
      <div style="display: flex;">
        <img src="@/assets/icon_popup_warn@2x.png" class="popup-image" alt="">
        <div class="popup-free-words">
          <div>冻结用户</div>
          <div class="tips">确定冻结吗？</div>
        </div>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <div class="footer-bottom-flex">
          <div
            style="margin-right: 10px;"
            class="query-common-small-customer-button"
            @click="freezePersonMethods"
          >
            <div>确定</div>
          </div>
          <div @click="handleClose" class="query-default-small-customer-button">
            <div>取消</div>
          </div>
        </div>
        <!--        <el-button @click="handleClose">取 消</el-button>-->
      </span>
    </el-dialog>

    <WarnPanelDialog
      :status-prop="isShowWarning"
      @confirmHandler="confirmMethods"
      @cancelHandler="cancelMethods"
    />
  </div>
</template>
<script>
import md5 from "js-md5";
import moment from "moment";
import CommonTable from '@/components/Table/commonTable'
import { customerManager } from './tableCol/customerManager'
import {formatImageUrl} from "@/api/common";
import WarnPanelDialog from '@/components/WarnPanelDialog/index'
import * as service from './service'
import * as commonApi from "@/api/common";
import {deleteUserConsumer, getUserDetailById, saveUserConsumer, updateUserConsumer, userFreeze} from "./service";

export default {
  components: {
    CommonTable,
    WarnPanelDialog
  },
  data() {
    return {
      currentManagerName: '',
      isShowFree: false,
      endDate: '',
      users: {},
      openDetailType: '',
      openTimeModelText: '',
      isShowAddCustomer: false,
      uploadData: {
        forwardIconUrl: ''
      },
      selectTimer: [],
      uploadLoading: false,
      isShowAddCustomerSelect: false,
      isLoading: false,
      passwordType: true,
      confirmPasswordType: true,
      roleList: [],
      customerManagerList: [],
      customerManager,
      personManagerSearch: {
        userName: '',
        customerType: '',
        star: '',
        nickName: '',
        createTime: '',
        phone: '',
        pageNum: 1,
        pageSize: 20,
        createBy: ''
      },
      meetingServiceInfo: [],
      customerModalTitle: '',
      addPersonModel: {
        enterpriseName: '',
        businessLicense: '',
        contacts: '',
        referrer: '',
        password: '',
        managerId: '',
        idCardFront: '',
        idCardBack: '',
        idCardNo: '',
        phone: ''
      },
      openTimeModel: '',
      openTimeList: [
        {
          label: '一年',
          value: 0
        },
        {
          label: '一个月',
          value: 1
        },
        {
          label: '一周',
          value: 2
        },
        {
          label: '一天',
          value: 3
        },
        {
          label: '其他',
          value: 4
        }
      ],
      personManagerList: [],
      total: 0,
      personClickCache: {},
      isShowWarning: false,
      isShowAddPerson: false,
      usersAddrules: {
        enterpriseName: [
          { required: true, message: '请输入企业名称', trigger: 'change' }
        ],
        contacts: [
          { required: true, message: '请输入联系人', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' }
        ]
      },
      delPersonList: [],
      addCustomType: '',
      setDatList: [],
      freeObj: {},
      currentUserName: ''
    }
  },
  mounted() {
    this.getPersonList()
    this.getCustomerList()
    this.getSetList()
  },
  methods: {
    activeMeetingInfo(index) {
      this.meetingServiceInfo.forEach((item) => {
        item.active = false
      })

      this.meetingServiceInfo[index].active = true
      this.meetingServiceInfo.splice(0,0)
    },
    // 获取套餐列表
    getSetList() {
      service.getSetList({}).then((res) => {
        this.meetingServiceInfo = res.data.slice()
      })
    },
    getCustomerList() {
      const params = Object.assign({}, this.personManagerSearch)

      this.isLoading = true
      if(params.createTime) {
        params.createTime = moment(params.createTime).format("YYYY-MM-DD")
      }
      service.getCustomerList(params).then((res) => {
        console.log('res.data ---', res.data)
        this.isLoading = false
        let currentDate = new Date().getTime()
        res.data.rows.forEach((item) => {
          let expirationTime = new Date(item.expiration).getTime()
          if(expirationTime > currentDate && expirationTime <= (currentDate + 7 * 24 * 3600 * 1000)) {
            item.warning = true
          }
        })
        this.customerManagerList = res.data.rows.slice()
        this.total = res.data.total
      })
    },
    createRandomNumber() {
      let randomPass = ''
      let chars = "0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      let passwordLength = 8;
      for (let i = 0; i < passwordLength; i++) {
        let randomNumber = Math.floor(Math.random() * chars.length);
        randomPass += chars.substring(randomNumber, randomNumber +1);
      }

      this.addPersonModel.password = randomPass
    },
    copyPassMethods() {
      let text = document.getElementById("passwordVal").value;

      let copyInput = document.getElementById("copy");
      copyInput.value = text;
      copyInput.select();
      document.execCommand("copy");
      this.$message({ message: "复制成功", type: "success" });
    },
    addNewCustomerPerson() {
      if(this.addCustomType == '') {
        this.$message.error('请选择用户类型')
        return
      }

      if(this.openDetailType === 'look') {
        if(this.addCustomType === 'company') {
          this.customerModalTitle = '查看企业客户'
        } else {
          this.customerModalTitle = '查看普通用户'
        }
      } else {
        if(this.addCustomType === 'company') {
          this.customerModalTitle = '新增企业客户'
        } else {
          this.customerModalTitle = '新增普通用户'
        }
      }
      this.meetingServiceInfo[0].active = true
      this.isShowAddCustomer = true
    },
    uploadforwardIconUrl(file, fileds) {
      this.$ossOtherSCJTUpload(file).then((res) => {
        this.uploadLoading = false;
        if (res?.res.status === 200) {
          commonApi.accessFile(res?.name).then((res) => {
            this.addPersonModel[fileds] = res.data;
          });
        } else {
          this.$message.warning("文件上传失败");
        }
      });
    },
    beforeUploadMethods() {
      this.uploadLoading = true
    },
    confirmMutiDel() {
      if (this.delPersonList.length === 0) {
        this.$message.error('请选择删除的人员')
        return
      }
      this.isShowWarning = true
    },
    changeSelectionList(val) {
      this.delPersonList = val.slice()
    },
    confirmMethods() {
      const params = {
        userIds: ''
      }
      if (this.delPersonList.length > 0) {
        const delList = []
        this.delPersonList.forEach((item) => {
          delList.push(item.userId)
        })
        params.userIds = delList.join(',')
      }
      if (Object.keys(this.personClickCache).length > 0) {
        params.userIds = this.personClickCache.userId
      }

      service.deleteUserConsumer(params).then((res) => {
        this.personManagerSearch.pageNum = 1
        this.$message.success('删除成功')
        this.isShowWarning = false
        this.resetDelData()
        this.delPersonList = []
        this.getCustomerList()
      })
    },
    // 重置删除数据
    resetDelData() {
      this.personClickCache = Object.assign({}, {})
    },
    cancelMethods() {
      this.isShowWarning = false
      this.resetDelData()
    },
    freezePerson(row, status) {
      if(status == 1) {
        this.freeObj = Object.assign({}, row)
        this.isShowFree = true
      } else {
        this.freeObj = Object.assign({}, row)
        this.freezePersonMethods()
      }
    },
    freezePersonMethods() {
      const params = {
        userId: this.freeObj.userId,
        customerStatus: this.freeObj.customerStatus == 0?1: 0
      }

      service.userFreeze(params).then(() => {
        this.$message.success('操作成功')
        this.getCustomerList()
        this.handleClose()
      })
    },
    delPersonDetail(row) {
      console.log('点击删除 ---', row)
      this.personClickCache = Object.assign({}, row)
      this.isShowWarning = true
    },
    lookPersonDetail(row) {
      this.openDetailType = 'look'
      this.addCustomType = row.customerType == 1?'company': 'person'

      if(this.openDetailType === 'look') {
        if(this.addCustomType === 'company') {
          this.customerModalTitle = '查看企业客户'
        } else {
          this.customerModalTitle = '查看普通用户'
        }
      } else {
        if(this.addCustomType === 'company') {
          this.customerModalTitle = '新增企业客户'
        } else {
          this.customerModalTitle = '新增普通用户'
        }
      }

      // 找到对应的套餐id
      const findSetIndex = this.meetingServiceInfo.findIndex((result) => {
        return result.setId == row.setId
      })

      if(findSetIndex !== -1) {
        this.meetingServiceInfo[findSetIndex].active = true
      }


      service.getUserDetailById({userId: row.userId}).then((res) => {
        console.log('res.data ---', res.data)
        Object.keys(this.addPersonModel).forEach((key) => {
          this.addPersonModel[key] = res.data[key]
        })
        if(res.data.idCardFront) {
          commonApi.accessFile(res.data.idCardFront).then((result) => {
            this.addPersonModel.idCardFront = result.data;
          });
        }

        if(res.data.idCardBack) {
          commonApi.accessFile(res.data.idCardBack).then((result) => {
            this.addPersonModel.idCardBack = result.data;
          });
        }

        if(res.data.businessLicense) {
          commonApi.accessFile(res.data.businessLicense).then((result) => {
            this.addPersonModel.businessLicense = result.data;
          });
        }
        this.addPersonModel.userId = row.userId
        this.currentManagerName = res.data.managerName

        this.openTimeModelText = this.openTimeList.filter((result) => {
          return result.value == res.data.openType
        })[0].label

        this.openTimeModel = res.data.openType
        if(res.data.begin) {
          this.selectTimer = [res.data.begin, res.data.expiration]
        }

        this.isShowAddCustomer = true
      })
    },
    editPersonDetail(row) {
      this.openDetailType = 'edit'
      this.addCustomType = row.customerType == 1?'company': 'person'

      service.getUserDetailById({userId: row.userId}).then((res) => {
        Object.keys(this.addPersonModel).forEach((key) => {
          this.addPersonModel[key] = res.data[key]
        })

        this.openTimeModel = res.data.openType
        if(res.data.begin) {
          this.selectTimer = [res.data.begin, res.data.expiration]
        }

        if(res.data.idCardFront) {
          commonApi.accessFile(res.data.idCardFront).then((result) => {
            this.addPersonModel.idCardFront = result.data;
          });
        }

        if(res.data.idCardBack) {
          commonApi.accessFile(res.data.idCardBack).then((result) => {
            this.addPersonModel.idCardBack = result.data;
          });
        }

        if(res.data.businessLicense) {
          commonApi.accessFile(res.data.businessLicense).then((result) => {
            this.addPersonModel.businessLicense = result.data;
          });
        }
        this.addPersonModel.userId = row.userId
        if(this.addCustomType === 'company') {
          this.customerModalTitle = '编辑企业客户'
        } else {
          this.customerModalTitle = '编辑普通用户'
        }
        // 找到对应的套餐id
        const findSetIndex = this.meetingServiceInfo.findIndex((result) => {
          return result.setId == row.setId
        })

        if(findSetIndex !== -1) {
          this.meetingServiceInfo[findSetIndex].active = true
        }
        this.isShowAddCustomer = true
      })
    },
    submitAddNewCustomer() {
      this.$refs['addUsersForm'].validate((valid) => {
        if(valid) {
          const findStar = this.meetingServiceInfo.findIndex((result) => {
            return result.active
          })
          const params = Object.assign({}, this.addPersonModel)

          params.star = this.meetingServiceInfo[findStar].star
          params.setId = this.meetingServiceInfo[findStar].setId
          params.idCardFront = formatImageUrl(params.idCardFront)
          params.idCardBack = formatImageUrl(params.idCardBack)
          params.businessLicense = formatImageUrl(params.businessLicense)
          params.openType = this.openTimeModel
          if(params.openType == 4) {
            if(this.selectTimer.length === 0) {
              this.$message.error('请选择到期时间')
              return
            } else {
              params.begin = this.selectTimer[0]
              params.expiration = this.selectTimer[1]

              if(new Date(params.begin).getTime() < new Date().getTime()) {
                this.$message.error('开始时间不能小于当前时间')
                return
              }

              if(new Date(params.begin).getTime() == new Date(params.expiration).getTime()) {
                this.$message.error('开始时间不能等于结束时间')
                return
              }
            }
          } else {
            delete params.begin
            delete params.expiration
          }

          if(params.password) {
            params.password = md5(params.password)
          }

          params.customerType = this.addCustomType === 'person'?0: 1
          if(!(/^1[3456789]\d{9}$/.test(params.phone))){
            this.$message.error('请输入正确的手机号')
            return
          }
          if(params.idCardNo) {
            if(!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(params.idCardNo))){
              this.$message.error('请输入正确的身份证号')
              return
            }
          }

          this.isLoading = true
          if(params.userId) {
            if(!params.password) {
              delete params.password
            }
            service.updateUserConsumer(params).then((res) => {
              this.$message.success('编辑成功')
              this.isShowAddCustomer = false
              this.isLoading = false
              this.getCustomerList()
              this.handleClose()
            }).catch(() => {
              this.isLoading = false
            })
          } else {
            service.saveUserConsumer(params).then((res) => {
              this.$message.success('新增成功')
              this.isShowAddCustomer = false
              this.isLoading = false
              this.isShowAddCustomerSelect = false
              this.getCustomerList()
              this.handleClose()
            }).catch(() => {
              this.isLoading = false
            })
          }
        }
      })
    },
    showPwd(model) {
      this[model] = !this[model]
    },
    getRoleList() {
      const params = {
        roleName: '',
        pageNum: 1,
        pageSize: 20000000
      }
      service.getRoleList(params).then((res) => {
        this.roleList = res.data.rows.filter((result) => {
          return result.roleId != 1
        })
      })
    },
    queryMethods() {
      this.personManagerSearch.pageNum = 1
      this.getCustomerList()
    },
    getPersonList() {
      this.isLoading = true
      const params = Object.assign({}, this.personManagerSearch)
      service.getPersonList({pageSize: 200000000, pageNum: 1}).then((res) => {
        this.isLoading = false
        res.data.rows.forEach((item) => {
          if (!item.roleName) {
            item.roleName = '--'
          }
          item.userId = parseInt(item.userId, 10)
        })
        this.personManagerList = res.data.rows.slice()
      })
    },
    addNewPersonMethods() {
      this.openDetailType = 'edit'
      this.isShowAddCustomerSelect = true
    },
    handleClose() {
      this.isShowAddCustomer = false
      this.isShowAddCustomerSelect = false
      this.addCustomType = ''
      this.addPersonModel = Object.assign({}, {
        enterpriseName: '',
        businessLicense: '',
        contacts: '',
        password: '',
        idCardFront: '',
        idCardBack: '',
        idCardNo: '',
        referrer: '',
        phone: '',
        managerId: ''
      })
      this.freeObj = {}
      this.isShowFree = false
      this.meetingServiceInfo.forEach((item) => {
        item.active = false
      })
    },
    handleSizeChange(size) {
      this.personManagerSearch.pageSize = size
      this.getCustomerList()
    },
    handleCurrentChange(page) {
      this.personManagerSearch.pageNum = page
      this.getCustomerList()
    }
  }
}
</script>
<style scoped lang="scss">
    .copy-words{
      font-size: 14px;
      color: #E8212E;
      cursor: pointer;
      margin-left: 5px;
    }
    .query-customer-button{
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #FFFFFF;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(0deg, #E70514 0%, #EA5B64 100%);
      width: 62px;
      height: 32px;
      border-radius: 18px;
      position: absolute;
      right: 40px;
      top: 40px;
      cursor: pointer;
    }
    .add-customer-button{
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #FFFFFF;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(0deg, #E70514 0%, #EA5B64 100%);
      width: 134px;
      height: 36px;
      border-radius: 18px;
      cursor: pointer;
    }
    .add-customer-icon{
      width: 12px;
      height: 12px;
      margin-right: 8px;
    }
    .role-manager-container{
        padding: 15px;
        background: #F7F9FA;
    }
    .page-nation{
        margin-top: 15px;
        text-align: right;
    }
    .add-person-input{
        width: 100%;
    }
    .el-icon-view{
        cursor: pointer;
    }
    .do-list {
      span {
        display: inline-block;
        margin-right: 20px;
        cursor: pointer;
        color: #409EFF;
        &.del-button{
          color: #F56C6C;
        }
      }
    }

    .customer-label-title{
      padding: 0 15px 15px 0px;
      border-bottom: 1px solid #eee;
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: bold;
    }

    .customer-type-card-row{
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;
      position: relative;
      left: -10px;
    }
    .customer-type-card-col{
      margin-left: 10px;
      padding: 15px 25px;
      text-align: left;
      line-height: 2.4444;
      border: 1px solid #F0EEEE;
      width: 30%;
      margin-top: 10px;
      border-radius: 12px;
      cursor: pointer;
    }
    .customer-type-card-col-active{
      border: 1px solid #F56C6C;
    }
    .customer-type-card-title-flex{
      display: flex;
      .right{
        margin-left: 10px;
      }
    }
    .copyInput {
      position: absolute;
      top: -999;
      left: -999;
      opacity: 0;
    }
    .flex-common {
      display: flex;
    }
    .left-icon-image{
      width: 16px;
      height: 16px;
      margin-right: 8px;
    }
    .content-bottom-row{
      margin-top: 30px;
      display: flex;
      justify-content: space-between;

      .content-button-col-right{
        font-family: PingFang SC;
        font-weight: bold;
        color: #333333;
      }
    }

    .first-words{
      color: #C2212D;
      font-size: 24px;
    }

    .second-words{
      color: #724C40;
      font-size: 24px;
    }

    .default-words {
      color: #333333;
      font-size: 24px;
    }

    .set-icon-header{
      padding: 24px 24px 24px 24px;
      background: white;
      margin-bottom: 16px;
      border-radius: 15px;
    }
    .set-icon-button-row{
      margin-bottom: 16px;
    }
    .float-right{
      position: absolute;
      top: 10px;
      right: 10px;
    }

    .dot-class{
      width: 8px;
      height: 8px;
      border-radius: 50%;
      display: inline-block;
      margin-right: 2px;
    }
    .dot-gray {
      background: #BFBFBF;
    }
    .dot-green {
      background: #0BDBA8;
    }
    .popup-image{
      width: 24px;
      margin-right: 15px;
      height: 24px;
    }
    .popup-free-words{
      font-size: 16px;
      font-family: PingFang SC;
      font-weight: bold;
      color: #333333;

      .tips{
        font-size: 14px;
        font-family: PingFang SC;
        font-weight: 500;
        color: #666666;
        margin-top: 6px;
      }
    }
</style>
